<template>
	<div class="system-role-dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="700px">
			<el-form ref="roleDialogFormRef" :model="state.ruleForm" size="default" label-width="120px"
				v-loading="state.dataLoading" element-loading-background="rgba(255, 255, 255, 1)" label-position="left">
				<el-form-item label="所有菜单" :style="{'min-height':'100px'}">
					<el-tree v-if="state.dialog.isShowDialog" ref="treeRef" :data="state.menuData" :props="state.menuProps"
						show-checkbox class="menu-data-tree" node-key="id" />
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" :loading="state.btnLoading" @click="onSubmit" size="default">确认</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup name="systemMenuDialog">
import { systemApi } from '/@/api/system'
import { toolsApi } from '/@/api/tools'
import { useMenuApi } from '/@/api/menu'
import { setBackEndControlRefreshRoutes } from "/@/router/backEnd";
import { ElMessage } from 'element-plus';
import { nextTick } from 'vue'
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义变量内容
const roleDialogFormRef = ref();
const treeRef = ref();
const state = reactive({
	ruleForm: {

	},
	query:{
		id:''
	},
	dialog: {
		isShowDialog: false,
		title: '修改菜单权限',
		submitTxt: '',
	},
	detailData: null,
	dataLoading: false,
	btnLoading: false,
	menuData: [],
	menuProps: {
		children: 'children',
		label: 'title',
	},
	allRole:[],
});

// 打开弹窗
const openDialog = (row) => {
	state.detailData = row;
	state.query.id=row.id;
	state.dialog.isShowDialog = true;
	state.dataLoading = true
	useMenuApi().menuAllMenus().then(res => {
		state.allRole = res.data
		toolsApi().menuTreeList(state.query).then(res => {
			state.dataLoading = false
			state.menuData =state.allRole
			if (row.menuIdList.length > 0) {
				row.menuIdList.forEach(item => {
					nextTick(() => {
						treeRef.value.setChecked(item, true, false)
					})
				})
			}
		}).catch(() => {
			state.dataLoading = false
		})
	}).catch(() => {
		
	})
};
// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
	closeDialog();
};
// 提交
const onSubmit = () => {
	const menuIdList = []
	const checkedMenus = treeRef.value.getCheckedNodes(false,true)
	if (checkedMenus.length) {
		checkedMenus.forEach(item => {
			menuIdList.push(item.id)
		})
	}
	state.btnLoading = true
	const apiData = {
		id: state.detailData.id,
		menuIds: menuIdList
	}
	systemApi().rolePermissions(apiData).then(res => {
		state.btnLoading = false
		ElMessage.success('操作成功');
		closeDialog();
		emit('refresh');
		location.reload()
	}).catch(() => {
		state.btnLoading = false
		closeDialog();
		emit('refresh');
	})

};

// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style scoped lang="scss"></style>
